package com.acme.bankapp.server;

import java.io.*;
import java.net.*;
import java.util.*;

public class BankClient {
	Socket requestSocket;
	ObjectOutputStream out;
	ObjectInputStream in;
	Scanner scan = new Scanner(System.in);
	String message;
	
	void connect(String host, int port) throws UnknownHostException, IOException {
		requestSocket = new Socket(host, port);		
		System.out.println("connected to localhost in port 1234");
		out = new ObjectOutputStream(requestSocket.getOutputStream());
		in  = new ObjectInputStream(requestSocket.getInputStream());
	}

	void disconnect() throws IOException {
		in.close();
		out.close();
		requestSocket.close();
	}
	
	void ask() {
		message = scan.nextLine();
		sendMessage(message);
	}
	
	void run() throws UnknownHostException, IOException {
		this.connect("localhost", 1234);
		System.out.println("server>" + receiveMessage());
		sendMessage("hi server");
		do {
			ask();
		} while (!message.equals("bye"));
		this.disconnect();
	}

	public String receiveMessage() {
		String msg = null;
		try {
			msg = (String)in.readObject();
			System.out.println("server>" + msg);
		} catch (ClassNotFoundException | IOException e) {
			e.printStackTrace();
		}
		return msg;
	}
	
	void sendMessage(final String msg) {
		try {
			out.writeObject(msg);
			out.flush();
			System.out.println("client>" + msg);
		} catch (IOException ioException) {
			ioException.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		BankClient client = new BankClient();
		try {
			client.run();
		} catch (UnknownHostException e) {
			System.out.println("Trying to connect to unknown host!");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
